/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.service.table.impl;

import com.je.common.base.util.StringUtil;
import com.je.meta.model.view.ViewColumn;
import com.je.meta.service.table.BuildAssociationDDLService;
import com.je.meta.service.table.Entry;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("moreJoinDDLService")
public class BuildMoreJoinDDLServiceImpl implements BuildAssociationDDLService {
    @Override
    public String createDdl(String template, List<ViewColumn> associationList) {
        ViewColumn viewColumn =associationList.get(0);
        String tableCodes = viewColumn.getMainTableCode();
        StringBuilder DDL = new StringBuilder();
        for(ViewColumn item:associationList){
            String mainTableCode = item.getMainTableCode();
            String targetTableCode = item.getTargetTableCode();
            String mainColumn = item.getMainColumn();
            String targetColumn = item.getTargetColumn();
            String formula = item.getFormula();
            DDL.append(formula).append(" ").append(targetTableCode).append(" ON " );
            if(StringUtil.isNotEmpty(mainTableCode)){
                DDL.append(mainTableCode).append(".");
            }
            DDL.append(mainColumn);
            DDL.append("=");
            if(StringUtil.isNotEmpty(targetTableCode)){
                DDL.append(targetTableCode).append(".");
            }
            DDL.append(targetColumn);
            DDL.append(" ");
        }
        Map<String,String> map = new HashMap<>();
        map.put("tableCodes",tableCodes);
        map.put("joinDDL",DDL.toString());
        return formatTemplate(template, Entry.build("tableCodes",tableCodes),Entry.build("joinDDL",DDL.toString()));
    }
}
